package my2Cents.tools;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.geom.GeneralPath;

import my2Cents.BodyState;
import my2Cents.Sandbox;
import my2Cents.Util;
import net.phys2d.math.Vector2f;
import net.phys2d.raw.BasicJoint;
import net.phys2d.raw.Body;
import net.phys2d.raw.CollisionEvent;
import net.phys2d.raw.StaticBody;
import net.phys2d.raw.shapes.PCircle;

public class MoverTool extends AbstractPhysTool {
	protected Body currentBody;
	protected BasicJoint joint;
	private Vector2f startOffset;
	protected int osize = 5;
	
	public MoverTool() {
		thinkLevel = AbstractPhysTool.THINKLEVEL_MAX;
		setGhostColor(AbstractPhysTool.GHOSTCOLOR_MOVE);
		setDescription(
				"Click on an object and drag to\n" +
				"move the object around."
			);
	}
	
	public void startTool(MouseEvent arg0) {
		super.startTool(arg0);
		osize = 20;
		currentBody = Util.selectBody(arg0.getX(), arg0.getY(), getWorld());
		if(currentBody == null) {
			endTool(arg0);
		}
		if(Util.getHandle() != null && currentBody != null) {
			startOffset = new Vector2f();
			startOffset.x = arg0.getX() - currentBody.getPosition().getX();
			startOffset.y = arg0.getY() - currentBody.getPosition().getY();

			Vector2f zero = new Vector2f(arg0.getX(),arg0.getY());

			Vector2f delta = startOffset;
			currentBody.setPosition(arg0.getX() - delta.x, arg0.getY() - delta.y);
			if(!(currentBody.isStatic())) {
				joint = new BasicJoint(Util.getHandle(), currentBody, zero);
				getWorld().add(joint);
			}
		}
	}
	
	public void toolThink(MouseEvent arg0) {
		Body handle = Util.getHandle();
		if(handle != null && currentBody != null) {
			handle.setPosition(arg0.getX(),arg0.getY());
			if(!sandbox.GO() || (currentBody.isStatic())) {
				if(currentBody != null) {
					Vector2f delta = startOffset;
					currentBody.setPosition(arg0.getX() - delta.x, arg0.getY() - delta.y);
				}
			}
		}
	}
	
	public void drawGhost(Graphics2D g) {
		osize--;
		if(osize >= 0) {
			setGhostOutlineSize(osize);
		}
		super.drawGhost(g);
	}
	
	public void endTool(MouseEvent arg0) {
		if(joint != null) {
			getWorld().remove(joint);
			joint = null;
		}
		Util.clearHandle(getWorld());
		if(currentBody != null) {
			currentBody = null;
		}
		super.endTool(arg0);
	}
	
	public boolean canDraw() {
		return (currentBody != null && inUse);
	}
	
	
	public GeneralPath getGhostPath() {
		if(currentBody != null) {
		return currentBody.getShape().getGeneralPath(
				(Vector2f) currentBody.getPosition(),
				currentBody.getRotation());
		}
		return new GeneralPath();
	}
}
